#!/usr/bin/python
# -*-coding:utf-8 -*-
import time
import json
import pickle
import datetime
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import platform
import os


class TouTiao:
    def __init__(self):
        # 采用谷歌浏览器
        chrome_opt = webdriver.ChromeOptions()
        chrome_opt.add_argument('--no-sandbox')  # Bypass OS security model
        # applicable to windows os only
        chrome_opt.add_argument('--disable-gpu')
        # chrome_opt.add_argument('start-maximized')
        chrome_opt.add_argument('disable-infobars')
        chrome_opt.add_argument("--disable-extensions")
        chrome_opt.add_argument('--disable-dev-shm-usage')
        chrome_opt.add_argument('window-size=1920x1480')
        sys = platform.system()
        print(sys)
        if sys == "Windows":
            print("sys=OS is Windows!!!")
            self.cookpath="D:\\code\\go\\src\\gitee.com\\wang_cyi\\TryEverything\\python\\toutiao\\cookies.pkl"
            path = r"D:\code\go\src\gitee.com\wang_cyi\TryEverything\python\toutiao\chromedriver\chromedriver.exe"
        elif sys == "Linux":
            print("sys=OS is centos!!!")
            path = r"/root/local/python/chromedriver/chromedriver"
            self.cookpath="/root/local/python/cookies.pkl"
            chrome_opt.add_argument("--headless")
            # 后台运行，不弹出浏览器
        if os.path.exists(self.cookpath) == True:
            self.cookies = pickle.load(open(self.cookpath, "rb"))
        self.browser = webdriver.Chrome(
            executable_path=path, chrome_options=chrome_opt)

    def loginWithCookies(self):
        """
        跳转微头条
        :return:
        """
        if self.cookies is None:
            self.login()
        self.browser.get(
            "https://mp.toutiao.com")
        self.cookies = pickle.load(open(self.cookpath, "rb"))
        for cookie in self.cookies:
            if 'expiry' in cookie:
                cookie['expiry'] = int(cookie['expiry'])
            self.browser.add_cookie(cookie)
        time.sleep(1)
        self.browser.refresh()

    def postWeiToutiao(self, content):
        print("postWeiToutiao begin")

        """
        今日头条：格言提醒
        """
        # load
        self.browser.get(
            "https://mp.toutiao.com/profile_v3/weitoutiao/publish")
        time.sleep(5)
        # 微头条内容框
        # presence_of_element_located（locator）：判断某个元素是否存在DOM中
        weitoutiao_content = WebDriverWait(self.browser, 10).until(EC.presence_of_element_located(
            (By.CSS_SELECTOR, ".ProseMirror")))   
        # CSS选择器 https://www.w3school.com.cn/cssref/css_selectors.asp
        # https://github.com/seleniumhq/selenium/issues/1480
        # div CLASS .intro id .
        weitoutiao_content.send_keys(content)
        #https://blog.csdn.net/weixin_44065501/article/details/89314538
        weitoutiao_content.send_keys(Keys.ENTER)
        print("step1-------------")
        time.sleep(5)

        # 点击发布 
        #https://my.oschina.net/u/4273790/blog/3807807
        actions = ActionChains(self.browser)
        weitoutiao_send_btn = self.browser.find_element_by_css_selector(".byte-btn.byte-btn-primary.byte-btn-size-default.byte-btn-shape-square.publish-content")  # 双击按钮
        weitoutiao_send_btn.send_keys(Keys.SPACE)
        print("step2-------------")

    def login(self):
        self.browser.get("https://mp.toutiao.com")
        time.sleep(30)
        cookies = self.browser.get_cookies()
        pickle.dump(cookies, open("cookies.pkl", "wb"))
        print("login success")

    def close(self):
        #self.browser.close()
        self.browser.quit()


 # https: // www.programcreek.com/python/example/88674/selenium.webdriver.support.expected_conditions.element_to_be_clickable
 # https://github.com/Tangnameless/WeiboSpider
if __name__ == '__main__':

    # https://www.yht7.com/news/17483
    today = datetime.date.today()
    y = datetime.datetime.now().year  # 获取年份
    m = datetime.datetime.now().month  # 获取月份
    d = datetime.datetime.now().day  # 获取“日”

    targetDay = datetime.date(y, m, d)  # 将输入的日期格式化成标准的日期
    dayCount = targetDay - \
        datetime.date(targetDay.year - 1, 12, 31)  # 减去上一年最后一天

    msg = "2分钟养成一个小好习惯："
    msg += "\r\n"
    msg += "今天是"
    msg += time.strftime("%Y-%m-%d", time.localtime())
    msg += "\r\n"
    msg += "2021年第"
    msg += time.strftime("%W")
    # https://blog.csdn.net/jerry_1126/article/details/80864048
    msg += "周 "
    msg += "\r\n"
    msg += "22点入睡提醒 "
    msg += str(dayCount.days)
    msg += "天"
    msg += "\r\n"
    msg += "为了明天早起,你必须采用预先承诺方法来抵挡美杜莎的诱惑"
    msg += "\r\n"
    msg += "行动要点：在回家之前提醒：手机放客厅，不放卧室 21 22 23点 60分钟强制锁屏"
    msg += "\r\n"
    msg += "晚上行思考: 意志力实验：直面自身欲望，但是不要付诸行定"
    msg += "\r\n"
    msg += "接下来一周里可以用以下 4个步骤来应对自己强烈的欲望 "
    msg += "1 ．承认自己脑海中的欲望 ，以及渴望某种事物的感觉  "
    msg += "\r\n"
    msg += "2 ．不要马上试着转移注意力或与之争论 。接受这种想法或感觉 ，提醒自己 “白熊 ”现象和 “反弹 ”理论  "
    msg += "\r\n"
    msg += "3 ．退一步考虑 ，意识到这种想法和感觉并不受你控制 ，但你可以选择是否将这些想法付诸实践  "
    msg += "\r\n"
    msg += "4 ．记住你的目标 ，提醒自己预先作出的承诺 。正如那些学生会提醒自己 ，他们答应过不偷吃巧克力  "
    tou_tiao = TouTiao()

    # 判断session是否过期
    first = False
    if os.path.exists("cookies.pkl") == False:
        first = True
     
    if first == True :
        tou_tiao.login()
        tou_tiao.close()
    else:
        tou_tiao.loginWithCookies()
        tou_tiao.postWeiToutiao(msg)
        tou_tiao.close()
        print(msg)
